package xuegao.study.mall.admin.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class CustomDateDeserializer extends JsonDeserializer<String> {
    private static final DateTimeFormatter INPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter ISO_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateStr = p.getText();
        try {
            // 先尝试直接解析为ISO格式（如果已经是目标格式则直接返回）
            ISO_FORMATTER.parse(dateStr);
            return dateStr;
        } catch (DateTimeParseException e1) {
            // 如果不是ISO格式，尝试按自定义格式解析
            try {
                LocalDateTime localDateTime = LocalDateTime.parse(dateStr, INPUT_FORMATTER);
                return localDateTime.atZone(ZoneId.systemDefault()).format(ISO_FORMATTER);
            } catch (DateTimeParseException e2) {
                throw new IOException("日期格式不合法，支持的格式为: yyyy-MM-dd HH:mm:ss 或 ISO 8601格式", e2);
            }
        }
    }

    public static void main(String[] args) {
        String dateStr = "2025-08-09T08:43:57.158Z";
        try {
            // 先尝试直接解析为ISO格式（如果已经是目标格式则直接返回）
            ISO_FORMATTER.parse(dateStr);
            System.err.println(dateStr);
        } catch (DateTimeParseException e1) {
            // 如果不是ISO格式，尝试按自定义格式解析
            try {
                LocalDateTime localDateTime = LocalDateTime.parse(dateStr, INPUT_FORMATTER);
                String format = localDateTime.atZone(ZoneId.systemDefault()).format(ISO_FORMATTER);
                System.out.println(format);
            } catch (DateTimeParseException e2) {
                e2.printStackTrace();
            }
        }
    }

}